<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: GetGoods.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\goods;

use app\api\model\dao\Goods;
use app\api\model\dao\GoodsAttr;
use app\api\model\dao\GoodsBrands;
use app\api\model\dao\GoodsSpec;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;

class GetGoods extends PageBase
{

    private $objGoods;
    private $objGoodsBrands;
    private $objGoodsSpec;
    private $objGoodsAttr;

    public function __construct()
    {
        parent::__construct();

        $this->objGoods = new Goods();
        $this->objGoodsBrands = new GoodsBrands();
        $this->objGoodsSpec = new GoodsSpec();
        $this->objGoodsAttr = new GoodsAttr();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'goods_id' => 'require',
        ];
        $msg = [
            'goods_id.require' => '商品ID必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }

        $goods_id = isset($param['goods_id']) ? intval($param['goods_id']) : 0;

        // 商品信息
        $ret = $this->objGoods->getGoods($goods_id);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }

        // 加上品牌名称
        $brand_id = $ret[0]['brand_id'];
        $brand = $this->objGoodsBrands->getGoodsBrands($brand_id);
        $brand_name = $brand[0]['brand_name'];
        $ret[0]['brand_name'] = $brand_name;

        // 加上折扣
        $ret[0]['discount'] = '' . round($ret[0]['shop_price'] / $ret[0]['market_price'], 2) * 10;

        // 加上规格
        $goodsSpec = $this->objGoodsSpec->getGoodsSpecByGoodsid($goods_id);

        // 商品属性
        $goodsAttr = $this->objGoodsAttr->getGoodsAttr($goods_id);

        $this->data = array(
            'goods' => $ret[0],
            'goods_spec' => $goodsSpec,
            'goods_attr' => $goodsAttr,
            'coupon' => [
                ['coupon_name' => '包邮', 'desc' => '双十一限时特价 全场满99包邮'],
                ['coupon_name' => '赠品', 'desc' => '赠送同款手办精美钥匙扣'],
                ['coupon_name' => '会员', 'desc' => '会员折扣'],
            ],
            'tags' => [
                '正品保障',
                '七天包换',
                '特殊包装',
                '温馨礼物',
            ],
        );
        return $this->getRes();
    }
}
